package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Slf4j
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

    @Autowired
    private     BrowsingHistoryMapper  browsingHistoryMapper;


    //        根据 用户 id 和 房间id 保存 用户浏览记录
    // @Async  当前 任务(saveHistory方法) 会 异步执行 ， 为了提升效率
    @Async
    @Override
    public void saveHistory(Long userId, Long id) {
        log.info("保存浏览房间的详情信息--->当前的线程:{}",Thread.currentThread().getName());

//        1、根据 userId 和 房间id 查询数据库
        LambdaQueryWrapper<BrowsingHistory>   browsingHistoryWrapper =  new LambdaQueryWrapper<>();
        browsingHistoryWrapper.eq(BrowsingHistory::getUserId ,userId);
        browsingHistoryWrapper.eq(BrowsingHistory::getRoomId , id);
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(browsingHistoryWrapper);

        if (browsingHistory != null) {
//        2、如果存在，说明已经浏览过 ， 修改 浏览时间即可
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        }else{
//        3、如果不存在，将 用户id 、房间id 、浏览时间都添加到数据库中即可
            browsingHistory = new BrowsingHistory();
            browsingHistory.setUserId(userId);
            browsingHistory.setRoomId(id);
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.insert(browsingHistory);
        }

    }

    /***
     *   根据 当前  用户id 查询 当前 用户 浏览 房间 历史信息
     * @param iPage
     * @param userId   当前用户id
     * @return
     */
    @Override
    public IPage<HistoryItemVo> selectBrowsingHistory(IPage<HistoryItemVo> iPage, Long userId) {

        IPage<HistoryItemVo>   result =  browsingHistoryMapper.selectBrowsingHistory(iPage , userId);

        return result;
    }
}